﻿using System.Collections.Generic;
using System.Linq;
using QDT.Common;
using QDT.Core;
using QDT.Core.Deals;

namespace QDT.Services.Credits
{
    public class CreditService : ServiceBase, ICreditService
    {
        public Credit GetCreditorById(int id)
        {
            return DbProvider.GetByID<Credit>(id);
        }

        public IPagedList<Credit> GetCreditPaged(int? page, int? userId = null, int? projectId = null, bool? isAssign = null, bool? isRepay = null, int assignmentId = 0, int pageSize = 10)
        {
            var filter = PredicateExtensionses.True<Credit>();
            if (userId.HasValue) filter = filter.And(x => x.UserID == userId);
            if (projectId.HasValue) filter = filter.And(x => x.ProjectID == projectId);
            if (isAssign.HasValue) filter = filter.And(x => x.IsAssign == isAssign);
            if (isRepay.HasValue) filter = filter.And(x => x.IsRepay == isRepay);
            if (assignmentId != 0) filter = filter.And(x => x.AssignmentID == assignmentId);
            var pageNumber = page ?? 1;

            var source = DbProvider.D<Credit>().Where(filter)
                                   .OrderByDescending(x => x.ID);
            return source.ToPagedList(pageNumber - 1, pageSize);
        }

        public ICollection<Credit> GetCreditList(int? userId, int? projectId, bool? isRepay, int assignmentId = 0)
        {
            if (userId == null && projectId == null && assignmentId == 0) return null;

            var filter = PredicateExtensionses.True<Credit>();
            if (userId.HasValue) filter = filter.And(x => x.UserID == userId);
            if (projectId.HasValue) filter = filter.And(x => x.ProjectID == projectId);
            if (assignmentId != 0) filter = filter.And(x => x.AssignmentID == assignmentId);
            if (isRepay.HasValue) filter = filter.And(x => x.IsRepay == isRepay);
            filter = filter.And(x => x.Money > 0);

            return DbProvider.D<Credit>().Where(filter).ToList();
        }

        public IPagedList<Credit> GetCanAssigmentCredit(int userId,int page=1, int pageSize = 10) {
            
            const int repayStatus = (int) CreditStatus.Repay;

            var source = DbProvider.D<Credit>().Where(x => x.UserID == userId && x.InnerStatus == repayStatus && x.Money > 0 && !x.IsAssign && !x.IsEasy).OrderByDescending(x => x.ID);

            return source.ToPagedList(page - 1, pageSize);
        }
    }
}
